package com.dman.multi.proxy;

import java.io.IOException;
import java.net.Proxy;
import java.net.URL;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;

public class ProxyDelegator implements ProxyHandler {

	private static ProxyDelegator proxyDelegator;
	private Map<Proxy.Type, ProxyHandler> proxyTypeHandlers = null;
	
	private ProxyDelegator(){
		proxyTypeHandlers = new HashMap<Proxy.Type, ProxyHandler>();
		proxyTypeHandlers.put(Proxy.Type.HTTP, new HTTPProxyHandler());
		proxyTypeHandlers.put(Proxy.Type.SOCKS, new Socks5ProxyHandler());
		proxyTypeHandlers.put(Proxy.Type.DIRECT, new NoProxyHandler());
	}

	@Override
	public boolean connect(SocketChannel sockChannel, ProxyAdaptor proxyAuth, URL url) throws IOException {
		return proxyTypeHandlers.get(proxyAuth.getProxy().type()).connect(sockChannel, proxyAuth, url);
	}

	@Override
	public String identifyProtocol(URL url, ProxyAdaptor proxyAuth) throws IOException{
		return proxyTypeHandlers.get(proxyAuth.getProxy().type()).identifyProtocol(url, proxyAuth);
	}
	
	public static ProxyDelegator getInstance(){
		if(proxyDelegator == null){
			synchronized (ProxyDelegator.class) {
				if(proxyDelegator == null)
					proxyDelegator = new ProxyDelegator();
			}
		}
		return proxyDelegator;
	}
}
